package com.gjt.clientSocket;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with Intel IDEA.
 *
 *  使用客户端Socket 读取服务器数据
 *
 * @Auther: gjt
 * @Date: 2024/4/8 6:09
 */
public class DaytimeClient {

    public static void main(String[] args) {

        String hostname = args.length > 0? args[0] : "time.nist.gov";

        // 这句不只是创建一个Socket 对象，还建立了网络连接
        try(Socket socket = new Socket(hostname,13)){
            // 设置socket 超时时间
            socket.setSoTimeout(15000);
            // 从socket中获取数据流
            InputStream inputStream = socket.getInputStream();
            InputStreamReader reader = new InputStreamReader(inputStream,"ASCII");

            StringBuilder time = new StringBuilder();
            for(int c = reader.read(); c !=-1; c =reader.read()){
                time.append((char)c);
            }
            // 60407 24-04-07 22:19:45 50 0 0 509.0 UTC(NIST) *

            System.out.println(parseDate(time.toString()));
        }catch (IOException e){
            e.printStackTrace();
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }


    // 解析时间
    static Date parseDate(String s) throws ParseException {
        String[] piece = s.split(" ");
        String dateTime = piece[1] + " " + piece[2] + " UTC";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yy-MM-dd hh:mm:ss z");
        return simpleDateFormat.parse(dateTime);
    }
}
